package top.shiyiri.pojo;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author Aunean
 * @date 2022/1/24 19:08
 */
public class Dom4jTest {

    @Test
    public void test1() throws Exception {
        //创建一个SaxReader输入流，去读取xml配置文件，生成Document对象
        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read("src/books.xml");
        System.out.println(doc);
    }

    /*
      读取books.xml生成的Book类
     */
    @Test
    public void test2() throws Exception {
        //1.读取books.xml文件
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read("src/books.xml");
        //2.通过Document文档获取根元素
        Element rootElement = document.getRootElement();
//        System.out.println(rootElement);
        //3.通过根元素获取book标签对象
        //element()和elements()都是通过标签名查找子元素
        List<Element> books = rootElement.elements("book");
        //4.遍历，处理每个books标签转换为Book类
        for (Element book : books) {
            //asXML()：把标签对象转换为标签字符串
            //System.out.println(book.asXML());
            //getText()：可以获取标签中的文本内容
            Element nameElement = book.element("name");
            //System.out.println(nameElement.getText());
            //直接获取指定标签中的文本内容
            String price = book.elementText("price");
            String author = book.elementText("author");
            String snValue = book.attributeValue("sn");
//            System.out.println(price);
//            System.out.println(author);
            System.out.println(new Book(snValue, nameElement.getText(), author, BigDecimal.valueOf(Double.parseDouble(price))));
        }
    }
}
